/*
 * AutoKey.cpp
 *
 *  Created on: 2021��5��7��
 *      Author: sunjipeng
 */
#include "AutoKey.h"

void AutoKey::init()
{
	pinMode(this->left_pin, INPUT_PULLUP);
	pinMode(this->right_pin, INPUT_PULLUP);
}

void AutoKey::run()
{
	if (digitalRead(this->left_pin) == LOW)
	{
		// �հ���ʱ���л�״̬
		if (state != State::LeftDown)
		{
			state = State::LeftDown;
			idleTm = 0;
		}
		buzzer.beep();
		morse.FireDit();
		// ʹ�� vTaskDelay ������ delay ����������������
		vTaskDelay(dit_tm / portTICK_PERIOD_MS);
		buzzer.stop();
		vTaskDelay(dit_tm / portTICK_PERIOD_MS);
	}
	else if (digitalRead(this->right_pin) == LOW)
	{
		if (state != State::RightDown)
		{
			state = State::RightDown;
			idleTm = 0;
		}
		buzzer.beep();
		morse.FireDah();
		vTaskDelay((dit_tm * 3) / portTICK_PERIOD_MS);
		buzzer.stop();
		vTaskDelay(dit_tm / portTICK_PERIOD_MS);
	}
	else
	{
		if (state != State::Idle)
		{
			// ��תΪ����״̬����ʼ��ʱ
			state = State::Idle;
			idleTm = millis();
		}
		else
		{
			if (idleTm != 0)
			{
				unsigned long ms = millis();
				unsigned int gap = ms - idleTm;
				if (gap > dit_tm * 3)
				{
					// todo
					char c = morse.GetRst();
					if (c != 0)
					{
						ui.fire_char(c);
						//Keyboard.print(c);
					}
					if (gap > dit_tm * 7)
					{
						// todo
						ui.fire_char(' ');
						//Keyboard.print(" ");
						// ����ʱ����㲻��ʱ����ʾ��ʱ��ɣ����ô��������ַ��Ϳո�
						idleTm = 0;
					}
				}
			}
		}
	}
	// vTaskDelay(1 / portTICK_PERIOD_MS);
}
